<?php

namespace App\Jobs;

use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;

class UpdateUserBalance implements ShouldQueue,ShouldBeUnique
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $user;
    protected $amount;
    protected $orderId;

    public function __construct(User $user, int $amount, string $orderId)
    {
        $this->user = $user;
        $this->amount = $amount;
        $this->orderId=$orderId;
    }
    /**
     * 作业的唯一锁释放后的秒数。
     *
     * @var int
     */
    public $uniqueFor = 60;

    /**
     * 获取作业的唯一 ID。
     */
    public function uniqueId(): string
    {
        return $this->orderId;
    }
    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        //
        DB::transaction(function () {
            // 假设你的用户表里有一个balance字段
            $this->user->balance += $this->amount;
            $this->user->save();
        });
    }
}
